import aiChatApi from '@/api/ai/aiChatApi'
import CryptoJS from 'crypto-js'


export default class AiEngine {

	url;
	urlTemplateConfig;
	headerTemplateConfig;
	templateConfig;
	responseTemplateConfig;
	properties;
	sendMessageFunc;
	updateMessageFunc;

	constructor(url, urlTemplateConfig, headerTemplateConfig, templateConfig, responseTemplateConfig, properties, sendMessageFunc, updateMessageFunc) {
		this.url = url;
		this.urlTemplateConfig = urlTemplateConfig;
		this.headerTemplateConfig = headerTemplateConfig;
		this.responseTemplateConfig = responseTemplateConfig;
		this.templateConfig = templateConfig;
		this.properties = properties;
		this.sendMessageFunc = sendMessageFunc;
		this.updateMessageFunc = updateMessageFunc;
	}


	async startConnect() {
		var host = location.host
		var date = new Date().toGMTString();
		let tc = await aiChatApi.resolveTemplateConfig({
			"template": this.urlTemplateConfig,
			data: {
				...this.properties,
				host,
				date,
				url: this.url
			}
		})
		console.log(tc)
		this.getPostEngine(tc);

	}
	sendMessage() {

	}
	closeConnect() {

	}
	getPostEngine(url) {
		let httpUrl = new URL(url);
		let socket;
		if (httpUrl.protocol.indexOf("wss") != -1) {
			if ('WebSocket' in window) {
				socket = new WebSocket(url)
			} else if ('MozWebSocket' in window) {
				socket = new MozWebSocket(url)
			} else {
				alert('浏览器不支持WebSocket')
				return
			}
			socket.onopen = async e => {
				// sendMessage();
				let data = await this.sendMessageFunc();
				console.log("on open sendMessage", data)
				socket.send(data);


			}
			socket.onmessage = async e => {
				let dd = JSON.parse(e.data);
				console.log("on message", dd);
				let tc = await aiChatApi.resolveTemplateConfig({
					"template": this.responseTemplateConfig,
					data: {
						...this.properties,
						url: this.url,
						...dd
					}
				})

				if (!tc) {
					return;
				}
				console.log("on message1", tc);

				dd = JSON.parse(tc);
				if (dd.code != 0) {
					message.error(dd.message);
					return
				}

				let message = this.buildMessage(dd);
				this.updateMessageFunc(dd.status, message);
			}
			socket.onerror = e => {
				// clearTimeout(this.playTimeout)
				// this.setStatus('error')
				alert('WebSocket报错，请f12查看详情')
				console.log(e)
				// console.error(`详情查看：${encodeURI(url.replace('wss:', 'https:'))}`)
			}
			socket.onclose = e => {
				console.log("on close ", e)
				this.closeConnect();
			}
		}
	}

	buildMessage(dd) {
		let message = "";
		for (let t of dd.messageList) {
			message +=decodeURIComponent(t.content);
		}
		return message;
	}
}
